package org.kirin.ocr.util.image;

import cn.hutool.core.io.FileUtil;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageCropWithAWT {

    public static void main(String[] args) throws IOException {
        // 读取原始图片
//        File inputFile = new File("D:\\zmq\\work-software\\dynamic_datasource\\src\\main\\resources\\tess4j\\image\\1.jpg"); // 替换为你的实际图片路径


        FileUtil.loopFiles(new File("D:\\zmq\\work-software\\dynamic_datasource\\src\\main\\resources\\tess4j\\image"))
                .forEach(file -> {
                    BufferedImage originalImage = null;
                    try {
                        originalImage = ImageIO.read(file);
                        int x = 462;
                        int y = 348;
                        int width = 453;
                        int height = 605;
                        for (int i = 0; i < 4; i++) {
                            // 定义要截取的矩形范围 2285 934
                            Rectangle rectangle = new Rectangle(x, y, width, height);

                            generateImage(originalImage, rectangle, i, FileUtil.mainName(file));

                            x = x + width;
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });

    }

    private static void generateImage(BufferedImage originalImage, Rectangle rectangle, int index, String fileName) throws IOException {
        // 创建一个新的BufferedImage，大小为指定的矩形范围
        BufferedImage croppedImage = new BufferedImage(rectangle.width, rectangle.height, BufferedImage.TYPE_INT_RGB);

        // 获取新图像的图形上下文
        Graphics2D g2d = croppedImage.createGraphics();

        // 将原始图像中指定矩形范围内的内容绘制到新图像上
        g2d.drawImage(originalImage, 0, 0, rectangle.width, rectangle.height, rectangle.x, rectangle.y, rectangle.x + rectangle.width, rectangle.y + rectangle.height, null);

        // 释放图形上下文资源
        g2d.dispose();

        // 将截取后的图像保存到文件
        File outputFile = new File("D:\\zmq\\work-software\\dynamic_datasource\\src\\main\\resources\\tess4j\\split\\" + fileName + index + ".jpg"); // 替换为你想要保存的路径
        ImageIO.write(croppedImage, "jpg", outputFile);

        System.out.println("已成功生成指定范围的图像并保存到：" + outputFile.getAbsolutePath());
    }
}